package com.firstsource.networking.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import org.apache.commons.net.telnet.TelnetClient;
import org.zkoss.util.logging.Log;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zul.Textbox;

public class Telnet extends Thread {

	private Socket connection = null ;
	private InputStream in = null ;
	private OutputStream out = null ;
	private InetAddress addr = null ;
	private TelnetClient client = null ;
	private Desktop desktop = null ;

	public Telnet(String ipAddr, Desktop desktop) throws Exception {
		this.desktop = desktop ;
		addr = InetAddress.getByName(ipAddr) ;
		client = new TelnetClient("vt100") ;
		client.connect(addr) ;
		in = client.getInputStream() ;
		out = client.getOutputStream() ;
	}

	public void run() {
		Textbox terminal = (Textbox)desktop.getWebApp().getAttribute("console") ;
		Log logger = Log.lookup(Telnet.class) ;
		while (connection!=null) {
			try {
				Thread.sleep(50) ;
			} catch (InterruptedException ie) {
				logger.log(Level.WARNING, ie.hashCode(), ie) ;
			}
			try {
				int character = in.read() ;
			} catch (IOException e) {
				logger.log(Level.WARNING, e.hashCode(), e) ;
			}
		}
	}

	public void send(String chars) throws Exception {
		out.write(chars.getBytes()) ;
	}

	public void close() throws Exception {
		connection.close() ;
		connection = null ;
	}
}
